

//
//  MyWebViewController.m
//  OC注入JS
//
//  Created by YYY on 2018/1/4.
//  Copyright © 2018年 YYY. All rights reserved.
//

#import "MyWebViewController.h"

#import <JavaScriptCore/JavaScriptCore.h>

@interface MyWebViewController () <UIWebViewDelegate>

@property (nonatomic,strong)UIWebView *webView;

@property (nonatomic,strong)UIButton *rightBtn;

@property(nonatomic,strong)NSMutableArray *imagesArray;

@end

@implementation MyWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
    [self.view addSubview:self.webView];
    
    //加载本地html
    NSString *path = [[NSBundle mainBundle] pathForResource:@"testIndex.html" ofType:nil];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request1];
}

- (UIButton *)rightBtn
{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightBtn setTitle:@"点击" forState:UIControlStateNormal];
        [_rightBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(click)
            forControlEvents:UIControlEventTouchUpInside];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    }
    return _rightBtn;
}
- (UIWebView *)webView
{
    if (_webView == nil)
    {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _webView.delegate = self;
        _webView.scrollView.scrollsToTop = NO;
        _webView.backgroundColor = [UIColor whiteColor];
    }
    return _webView;
}

- (NSMutableArray *)imagesArray
{
    if (!_imagesArray)
    {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}
#pragma mark UIWebView delegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //request.URL.scheme             neng
    //request.URL                    neng://loadUrl/blog.csdn.net
    //request.URL.absoluteString     neng://loadUrl/blog.csdn.net
    //request.URL.resourceSpecifier  //loadUrl/blog.csdn.net
    NSString *urlStr = request.URL.absoluteString;
    if ([urlStr hasPrefix:@"neng://"])
    {
        //除去协议头
        NSString *urlContent = [urlStr substringFromIndex:[@"neng://" length]];
        NSLog(@"urlContent = %@",urlContent);
        NSArray *urls = [urlContent componentsSeparatedByString:@"/"];
        NSLog(@"urls = %@",urls);
        
        //去出方法名
        if (urls.count != 2)
        {
            return NO;
        }
        NSString *fullName = [NSString stringWithFormat:@"%@:",urls[0]];
        SEL method = NSSelectorFromString(fullName);
        
//取消警告
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self performSelector:method withObject:urls[1]];
# pragma clang diagnostic pop
        NSLog(@"方法名：%@ 传人参数：%@",fullName,urls[1]);
        
        return NO;
    }
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取JS标题
    //self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    //获取该UIWebView的javascript上下文
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //在调用前，设置异常回调
    [jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
        NSLog(@"%@", exception);
    }];
    //这也是一种获取标题的方法。
    JSValue *value = [jsContext evaluateScript:@"document.title"];
    //更新标题
    self.navigationItem.title = value.toString;
    
    //[self.webView stringByEvaluatingJavaScriptFromString:@"clickme()"];
}

- (void)loadUrl:(NSString *)urlString
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",urlString]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

- (void)click
{
    [self.webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function myFunction() { "   //定义myFunction方法
     "var field = document.getElementsByName('word')[0];"
     "field.value='WWDC2014';"
     "document.forms[0].submit();"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];  //添加到head标签中
    
    [self.webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
}

@end
